package org.ssi.web.tags.security;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import com.bjtech.domain.User;
import com.bjtech.web.util.Constants;

public final class UserSecurityTag extends TagSupport {
	private static final long serialVersionUID = 1L;

	private static String[] all = { Constants.CKMS,Constants.MANAGEMENT };

	private String id;

	private String name;

	private String page = Constants.MESSAGE;

	public int doStartTag() throws JspException {
		return (SKIP_BODY);
	}

	public int doEndTag() throws JspException {
		boolean valid = true;
		int userID = 0;
		User user = null;

		String[] names = name.split(",");
		if (name == null || name.length() == 0) {
			names = all;
		}

		HttpSession session = pageContext.getSession();
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();

		for (int i = 0; i < names.length; i++) {
			if ((session != null) && (session.getAttribute(names[i]) != null)) {
				user = (User) session.getAttribute(names[i]);
				userID = user.getUserId().intValue();
			}
			if (userID != 0)
				break;
		}
		String redirect="/admin";
		if (request.getServletPath().startsWith("/ckms")) {
			redirect = request.getContextPath() + "/ckms/";
		} else if (request.getServletPath().startsWith("/admin")) {
			redirect = request.getContextPath() + "/admin/";
		} else {
			redirect = request.getContextPath() + "/index.shtml";
		}

		if (userID == 0) {
			valid = false;
			request.setAttribute("error", "您还没有登录！或者会话期已过，请重新登录！&nbsp;");
		} else if (false) {
			valid = false;
			request.setAttribute("error", "您没有权限操作此功能，如有需要请与系统管理员联系！");
		}

		if (valid) {
			return (EVAL_PAGE);
		} else {
			try {
				pageContext.forward(page);
			} catch (Exception e) {
				throw new JspException(e.toString());
			}
			return (SKIP_PAGE);
		}
	}

	public void release() {
		super.release();
		this.id = null;
		this.name = null;
		this.page = Constants.MESSAGE;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPage() {
		return page;
	}

	public void setPage(String page) {
		this.page = page;
	}
}
